const fs = require('fs').promises;
const path = require('path');
const schedule = require('node-schedule');

// 配置对象（可根据项目需要调整）
const config = {
  folderPath: './uploads',       // 监控目录路径
  cronPattern: '*/30 * * * *',   // 每10分钟执行一次
  retentionMinutes: 10           // 保留时间（分钟）
};

class TimestampFileCleaner {
  constructor(config) {
    this.config = config;
    this.job = null;
  }

  /**
   * 从文件名提取时间戳
   * @param {string} filename 
   * @returns {Date|null}
   */
  extractTimestamp(filename) {
    const match = filename.replace('.db','').split("-");
    if (!match) return null;

    const timestampStr = match[1]; // 正则中第二个捕获组是时间戳
    try {
      return new Date(
        parseInt(timestampStr.substring(0, 4)),   // year
        parseInt(timestampStr.substring(4, 6)) - 1, // month
        parseInt(timestampStr.substring(6, 8)),    // day
        parseInt(timestampStr.substring(8, 10)),   // hour
        parseInt(timestampStr.substring(10, 12)),  // minute
        parseInt(timestampStr.substring(12, 14))   // second
      );
    } catch (e) {
      console.error(`[Cleaner] 时间戳解析失败: ${timestampStr}`, e);
      return null;
    }
  }

  /**
   * 执行清理任务
   */
  async executeCleanup() {
    const now = new Date();
    const cutoffTime = new Date(now - this.config.retentionMinutes * 60 * 1000);

    console.log(`[${now.toISOString()}] 清理 ${this.config.folderPath} 中早于 ${cutoffTime.toISOString()} 的文件`);

    try {
      const files = await fs.readdir(this.config.folderPath);
      let deletedCount = 0;

      await Promise.all(files.map(async (file) => {
        try {
          const fileDate = this.extractTimestamp(file);
          if (!fileDate || fileDate >= cutoffTime) return;

          const filePath = path.join(this.config.folderPath, file);
          await fs.unlink(filePath);
          deletedCount++;
          console.log(`[Cleaner] 已删除: ${file}`);
        } catch (err) {
          console.error(`[Cleaner] 处理文件 ${file} 失败:`, err);
        }
      }));

      console.log(`[Cleaner] 本次清理完成，共删除 ${deletedCount} 个文件`);
    } catch (err) {
      console.error('[Cleaner] 清理任务失败:', err);
    }
  }

  start() {
    if (this.job) this.stop();
    
    this.job = schedule.scheduleJob(this.config.cronPattern, async () => {
      await this.executeCleanup();
    });

    // 立即执行一次初始化清理
    this.executeCleanup(); 
    console.log(`[Cleaner] 启动定时清理任务，CRON: ${this.config.cronPattern}`);
  }

  stop() {
    if (this.job) {
      this.job.cancel();
      this.job = null;
    }
    console.log('[Cleaner] 定时清理已停止');
  }
}

// 使用示例
module.exports = (customConfig = {}) => {
  const finalConfig = { ...config, ...customConfig };
  return new TimestampFileCleaner(finalConfig);
};